/**
 * 
 */
package com.xored.glance.ui.controls.text.styled;

import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.swt.custom.ExtendedModifyEvent;
import org.eclipse.swt.custom.LineStyleEvent;
import org.eclipse.swt.custom.LineStyleListener;
import org.eclipse.swt.custom.StyledText;

import com.xored.glance.ui.sources.Match;
import com.xored.glance.ui.utils.TextUtils;

/**
 * @author Yuri Strot
 * 
 */
public class ListeningStyledTextSource extends AbstractStyledTextSource
		implements LineStyleListener {

	/**
	 * @param text
	 */
	public ListeningStyledTextSource(StyledText text) {
		super(text);
		text.addLineStyleListener(this);
	}

	@Override
	protected void doDispose() {
		super.doDispose();
		getText().removeLineStyleListener(this);
		refresh();
	}

	@Override
	protected StyledTextBlock createTextBlock() {
		return new StyledTextBlock(getText()) {
			@Override
			public void modifyText(ExtendedModifyEvent event) {
				matches = Match.EMPTY;
				super.modifyText(event);
			}
		};
	}

	public void show(Match[] matches) {
		this.matches = matches;
		refresh();
	}

	public void lineGetStyle(LineStyleEvent event) {
		if (matches.length > 0) {
			int offset = event.lineOffset;
			int length = event.lineText.length();

			int size = event.styles == null ? 0 : event.styles.length;
			TextPresentation presentation = new TextPresentation(new Region(
					offset, length), size);
			if (event.styles != null && event.styles.length > 0)
				presentation.replaceStyleRanges(event.styles);
			applyTextPresentation(presentation);
			event.styles = TextUtils.getStyles(presentation);
		}
	}

	private void refresh() {
		String text = getText().getText();
		getText().redrawRange(0, text.length(), false);
	}

	private void applyTextPresentation(TextPresentation presentation) {
		TextUtils.applyStyles(presentation, matches);
	}

	private Match[] matches = Match.EMPTY;
}
